#!/use/bin/perl # for syntax hilighting
use gri_secmgr qw(get_cookie_value got_cookie redirect_header);
use gri_database;
use gri_mime;
use Data::Dumper;

sub mm_docrepos_view_document {
my $sha1=shift;
my $lname=shift;
my $lp=shift;

	if(! got_cookie(name => "gri_dbm_intranet")) {
		print STDERR "mm_docrepos_vew_document: User not logged in.\n";
		return "Unable to get document details - user not logged in.";
	}
	my $mime_file=$::GRI_FRONTEND->get_variable("MIME_FILE");
	if(defined($mime_file)) {
		$mime_info=new gri_mime($mime_file);
	}
	my $v=get_cookie_value(name=>"gri_dbm_intranet");
	$v=~ s/\s+.*//;
	my $username=$v;

	# Work out whether use can access section and abort with
	# suitable error if not.

	my $db_dir=$::GRI_FRONTEND->get_global_directory("database");
	my $repos_dir=$::GRI_FRONTEND->get_global_directory("docrepos");
	my $docrepos_dir=$::GRI_FRONTEND->get_global_directory("docrepos");
	my $DB=new gri_database("$db_dir/gri.db");
	my ($res,$details)=$DB->get_details(sha1=>$sha1,lname=>$lname);
	if($res==0) {
		return "Specified document does not exist.";
	}
	if($res<0) {
		return "Error $res returned from get_details_by_sha1";
	}

	# However - first we the user's list of reader sections and double 
	# check one is in the list defined for this document sections.

	my $rr;
	($res,$rr)=$DB->get_user_sections(user=>$username,type=>"reader");
	if($res!=1) {
		return "Error $res returned from get_user_sections";
	}
	my @S=split(/,/,$details->{sections});
	my @readers=();
	for my $csection (@S) {
		if(grep {$_ eq $csection} @$rr) {
			push @readers,$csection;
		}
	}
	if(! @readers) {
		return "Error: You do not have permissions to view this document!";
	}

	# Ok - the user can view the document so the next step is view the
	# document and blurt it out...

	my $application=$mime_info->application($details->{original_name});
	if(!defined($application)) {
		$application="text/html";
	}

	# Dump out a header and then the document contents ...
	my $fd;
	open($fd,"$repos_dir/$details->{local_name}");
	if(!defined($fd)) {
		return "Error: Unable to open '$repos_dir/$details->{local_name}'.\n";
	}
	my $fname="download";
	my $ff=$details->{original_name}; 
	$ff=~ s/.*\.//;
	$fname.=".$ff";
	print "Content-Type: $application\nContent-disposition: attachment; filename=$fname\n\n";
	while(read($fd,$buff,1024)) {
		print $buff;
	}
	close($fd);
	exit(0);
}

1;

